package com.JFapp.controller;

import com.JFapp.domain.dto.CategoryDto;
import com.JFapp.domain.entity.Category;
import com.JFapp.domain.entity.ResponseResult;
import com.JFapp.domain.vo.ExcelCategoryVo;
import com.JFapp.eumns.AppHttpCodeEnum;
import com.JFapp.service.CategoryService;
import com.JFapp.utils.BeanCopyUtils;
import com.JFapp.utils.WebUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/content/category")
@ApiOperation("分类管理")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;


    @ApiOperation("导出分类")
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("分类.xlsx",response);
            //获取需要导出的数据
            List<Category> categoryVos = categoryService.list();

            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categoryVos, ExcelCategoryVo.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
                    .doWrite(excelCategoryVos);

        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }


    @GetMapping("/list")
    @ApiOperation("全分类查询")
    public ResponseResult selectCategory(Integer pageNum, Integer pageSize){
        return categoryService.selectCategory(pageNum,pageSize);
    }
    @ApiOperation("查询分类列表")
    @GetMapping("/listAllCategory")
    public ResponseResult getListAllCategory(){
        return categoryService.getListAllCategory();
    }
    @ApiOperation("查询分类详细")
    @GetMapping("/{id}")
    public ResponseResult getCategoryDetail(@PathVariable Long id){
        return categoryService.getCategoryDetail(id);
    }
    @ApiOperation("添加分类")
    @PostMapping()
    public ResponseResult addCategory(@RequestBody CategoryDto category){
        return categoryService.addCategory(category);
    }

    @ApiOperation("更新分类")
    @PutMapping()
    public ResponseResult updateCategory(@RequestBody Category category){
        return categoryService.updateCategory(category);
    }

    @ApiOperation("删除分类")
    @DeleteMapping("/{id}")
    public ResponseResult deleteCategory(@PathVariable Long id){
        return  categoryService.deleteCategory(id);
    }
}

